package club.dmyang.common.shiro;

import club.dmyang.entity.User;
import club.dmyang.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by brss on 2018/7/12.
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        return null;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //编写Shiro判断逻辑，判断用户名和密码是否正确
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;//用户传入的用户名和密码
        User dbUser = userService.findByUsername(token.getUsername());//数据库中的用户

        //1.判断用户名
        if (dbUser==null) {
            //用户名不存在
            return null;//shiro 底层会抛出UnknownAccountException
        }
        //2.判断密码：
        //第一个参数：principal意思主要的，相当与主键的意思，第二个参数：数据库密码，第三个参数：realm的名字
        SimpleAuthenticationInfo autheInfo = new SimpleAuthenticationInfo(dbUser, dbUser.getPassword(), "UserRealm");
        return autheInfo;
    }
}
